/*
 * @Date: 2022-03-25 09:17:45
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2022-08-22 10:49:41
 * @FilePath: \server\system\core\ws\ws.go
 */
package ws

import (
	"encoding/json"
	"fmt"
	"net/http"

	"go2admin_pure/system/core/config"
	"go2admin_pure/system/core/log"
)

const (
	TypeOnline  string = "online"
	TypeOffline string = "offline"
	TypeKick    string = "kick"
	TypeMsg     string = "msg"
)

type SendClass struct {
	Type    string `json:"type"`
	Content string `json:"content"`
}

var hub *Hub

func serveHome(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
}

//可以从chan获取在线用户
func Init() *Hub {
	//避免影响主程序
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("ws.init发生错误", err)
		}
	}()

	if hub == nil {
		hub = newHub()
		go hub.run()
		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			serveWs(hub, w, r)
		})
		err := http.ListenAndServe(fmt.Sprintf(":%d", config.Instance().App.WsPort), nil)
		if err != nil {
			log.Write(log.Error, err.Error())
		}
	}
	return hub
}

//在线用户
func OnlineIds() []int {
	r := make([]int, 0)
	temp_clients := Init().clients
	if len(temp_clients) > 0 {
		for c, v := range temp_clients {
			if v && c.Userdata != nil {
				r = append(r, c.Userdata.UserInfo.Id)
			}
		}
	}
	return r
}

//单独发送消息
func SendMsg(id int, msg string, msgtype string) {
	for c, v := range Init().clients {
		if c.Userdata != nil {
			if c.Userdata.UserInfo.Id == id && v {
				s := SendClass{Type: msgtype, Content: msg}
				d, _ := json.Marshal(s)
				c.Send <- d
			}
		}
	}
}

//广播消息
func Broadcast(msg string, msgtype string) {
	s := SendClass{Type: msgtype, Content: msg}
	d, _ := json.Marshal(s)
	Init().Broadcast <- d
}

//服务端实现下线用户
func Kick(id int) {
	for c, v := range Init().clients {
		if c.Userdata.UserInfo.Id == id && v {
			Init().unregister <- c
		}
	}
}
